package com.sky.task;

import cn.hutool.core.collection.CollectionUtil;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @program: sky-take-out
 * @description:
 * @author: 酷炫焦少
 * @create: 2024-11-20 08:19
 **/
@Component
@Slf4j
public class OrderTask {

    @Resource
    private OrderMapper orderMapper;

    // 每分钟执行一次，对于未支付的且超过15分钟的
    @Scheduled(cron = "0 1 * * * ?")
    public void processTimeoutOrder() {
        log.info("定时任务处理超时订单: {}", LocalDateTime.now());
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, LocalDateTime.now().minusMinutes(15));
        if (CollectionUtil.isNotEmpty(ordersList)) {
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("用户未支付，订单取消");
                orderMapper.update(orders);
            });
        }
    }

    // 每凌晨1点更新，派送中而没有点完成的
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        log.info("定时任务处理派送中订单: {}", LocalDateTime.now());
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().minusHours(1));
        if (CollectionUtil.isNotEmpty(ordersList)) {
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }
    }


}
